<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <div style="position: relative">
      <TaskTitle :icon-name="iconName" :title-name="titleName" :color="color" />
    </div>
    <div class="g-drawer-list-container">
      <div class="connect_divs">
        <div class="g-drawer-progress-container">
          <TitleSecondary title="审批流程图" />
          <ProgressStaus />
        </div>
        <ProgressGraph :data="form.nodeFlowCharts" />
        <TitleSecondary title="基本信息" />
        <AddMatterForm ref="form" :form="form" />
        <TitleSecondary v-if="isCurrent || isOver" title="处理结果" />
        <AddMatterResultForm
          v-if="isCurrent || isOver"
          ref="resultForm"
          :matter-id="matterId"
          :is-current="isCurrent"
          :result-form="resultForm"
          :delete-file-id.sync="deleteFileId"
          :is-over="isOver"
        />
      </div>
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="footerButtons"
      @click="handleButtonClick"
    />
    <DialogTransferMatter
      :visible.sync="visibleTransfer"
      :plan-id="matterId"
      @change="onClose"
    />
  </p-drawer>
</template>

<script>
import monent from 'moment';
import { postDeleteFile } from '@/api/order.js';
import AddMatterForm from './AddMatterForm.vue';
import AddMatterResultForm from './AddMatterResultForm.vue';
import { postSaveMatter } from '@/api/mattre.js';
import ProgressStaus from '@/components/task/ProgressStaus.vue';
import ProgressGraph from '@/components/task/ProgressGraph.vue';
import { getCurrentUser } from '@/api/public.js';
import DialogTransferMatter from '@/components/dialog/DialogTransferMatter.vue';

const defaultForm = {
  id: '',
  visitNo: '',
  matterNo: '',
  leadsName: '',
  topic: '',
  state: '',
  visitName: '',
  salesContractNo: '',
  opportunityName: '',
  opportunityNo: '',
  leadsNo: '',
  remark: '',
  createUserName: '',
  createTime: '',
  currentDepartmentName: '',
  createDepartmentName: '',
  currentUserName: '',
  nodeFlowCharts: [],
};
const defaultResultForm = {
  result: '',
  attachmentList: [],
  currentMatterTime: '',
};
export default {
  components: {
    AddMatterForm,
    ProgressStaus,
    ProgressGraph,
    AddMatterResultForm,
    DialogTransferMatter,
  },
  // mixins: [DrawerMixin],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    addState: {
      type: Boolean,
      default: false,
    },
    detail: {
      type: Object,
      default: () => ({}),
    },
    isFoot: {
      type: Boolean,
      default: false,
    },
    titleInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      resultForm: {
        ...defaultResultForm,
      },
      form: {
        ...defaultForm,
      },
      isCurrent: false,
      planIdNew: undefined,
      saleList: [],
      isEdit: false,
      currentUser: '',
      currentUserOrg: '',
      matterId: '',
      deleteFileId: [],
      nodeCode: '',
      processId: '',
      currentUserId: '',
      currentMatterTime: '',
      isOver: false,
      visibleTransfer: false,
    };
  },

  computed: {
    titleName() {
      const titleName =
        !this.isCurrent || this.isOver ? '跟进事项详情' : '跟进事项详情-待办';
      return titleName;
    },
    color() {
      const titleName = !this.isCurrent || this.isOver ? 'green' : 'blue';
      return titleName;
    },
    iconName() {
      const titleName = !this.isCurrent || this.isOver ? 'Det' : 'Todo';
      return titleName;
    },
    footerButtons() {
      const buttons = this.isCurrent
        ? this.nodeCode !== '2'
          ? [
              {
                key: 'submit',
                type: 'primary',
                label: '提交',
                auth: true,
              },
              {
                key: 'save',
                label: '保存',
                auth: true,
              },
              {
                key: 'retweet',
                label: '转他人处理',
                auth: true,
              },
              {
                key: 'close',
                label: '返回',
              },
            ]
          : [
              {
                key: 'close',
                label: '返回',
              },
            ]
        : [
            {
              key: 'close',
              label: '返回',
            },
          ];
      return buttons;
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.getCurrentInfo();
        if (!val) return;
        if (!this.addState) {
          const plan = this.detail || {};
          if (plan.nodeCode === '2') {
            this.isOver = true;
          }
          this.isCurrent = plan.isCurrent;
          this.matterId = plan.id;
          this.nodeCode = plan.nodeCode;
          this.processId = plan.processId;
          this.currentUserId = plan.currentUserId;
          this.form = {
            id: plan.id || '',
            visitNo: plan.visitNo || '',
            // salesGroupCode: plan.createUserGroup,
            // salesGroupCode:plan.salesGroupCode||'',
            matterNo: plan.matterNo || '',
            currentMatterTime: plan.currentMatterTime || '',
            topic: plan.topic || '',
            state: plan.state || '',
            visitName: plan.visitName || '',
            contractStatus: plan.contractStatus || '',
            salesContractNo: plan.salesContractNo || '',
            opportunityName: plan.opportunityName || '',
            remark: plan.remark || '',
            leadsNo: plan.leadsNo || '',
            opportunityNo: plan.opportunityNo || '',
            leadsName: plan.leadsName || '',
            currentUserName: plan.currentUserName || '',
            createUserName: plan.createUserName || '',
            createDepartmentName: plan.createDepartmentName || '',
            createTime: plan.createTime || '',
            currentDepartmentName: plan.currentDepartmentName || '',
            createDepartment: plan.createDepartment || '',
            nodeFlowCharts: plan.nodeFlowCharts || [],
          };
          this.resultForm = {
            attachmentList: plan.attachmentList,
            result: plan.result,
            currentMatterTime: plan.currentMatterTime,
          };
        }
      },
    },
    // addState: {
    //   handler(val) {
    //     console.log('val: ', val);
    //     if (val) {
    //       this.titleName = '新增订单';
    //       this.color = 'red';
    //       this.iconName = 'New';
    //     }
    //   },
    //   immediate: true,
    // },
    titleInfo: {
      handler(val) {
        this.titleName = val.titleName;
        this.color = val.color;
        this.iconName = val.iconName;
      },
      deep: true,
    },
  },
  created() {},
  methods: {
    clearList() {
      this.saleList = [];
    },
    async getCurrentInfo() {
      const result = await getCurrentUser();
      this.currentUser = result?.data?.data?.name || '';
      this.currentUserOrg = result?.data?.data?.departmentName || '';
      this.currentUserOrg = this.removalSame(this.currentUserOrg);
    },
    removalSame(obj) {
      obj = obj.replace(/\s*/g, '');
      const array = obj.split(',');
      console.log('array: ', array);
      const departmentName = [...new Set(array)].join(',');
      return departmentName;
    },
    onClose() {
      this.form = { ...defaultForm };
      this.isOver = false;
      this.isEdit = false;
      this.deleteFileId = [];
      this.$emit('update:isFoot', false);
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    async submitCallback() {
      const valid = await this.$refs.resultForm.validate();
      if (!valid) return new Promise(() => {});
      if (this.deleteFileId.length) {
        const result = await postDeleteFile(this.deleteFileId);
        this.deleteFileId = [];
      }
      const formInfo = JSON.parse(
        JSON.stringify(this.$refs.resultForm.resultForm)
      );
      if (!this.$refs.form.list.length) {
        formInfo.attachmentList = [];
      }
      const params = {
        id: this.form.id,
        attachmentList: this.$refs.resultForm.fileList,
        result: formInfo.result,
        isSubmit: true,
        visitNo: this.form.visitNo,
      };
      const result = await postSaveMatter(params);
      if (result.data.code === 0) {
        this.$message.success('提交成功！');
        this.closeCallback();
      }
    },
    async saveCallback() {
      const valid = await this.$refs.resultForm.validate();
      if (!valid) return new Promise(() => {});
      if (this.deleteFileId.length) {
        const result = await postDeleteFile(this.deleteFileId);
        this.deleteFileId = [];
      }
      const formInfo = JSON.parse(
        JSON.stringify(this.$refs.resultForm.resultForm)
      );
      if (!this.$refs.form.list.length) {
        formInfo.attachmentList = [];
      }
      const params = {
        id: this.form.id,
        attachmentList: this.$refs.resultForm.fileList,
        result: formInfo.result,
      };
      const result = await postSaveMatter(params);
      if (result.data.code === 0) {
        this.$message.success('保存成功！');
        this.closeCallback();
      }

      // const serialNumber = result?.data?.data?.serialNumber;
      // this.planIdNew = result?.data?.data?.id;
      // this.$refs.form.setForm(serialNumber);
    },
    retweetCallback() {
      this.visibleTransfer = true;
    },
    closeCallback() {
      this.onClose();
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>
<style lang="less" scoped>
.edit {
  position: absolute;
  top: 10px;
  right: 30px;
}
.connect_divs {
  overflow-x: hidden;
  height: calc(100vh - 50px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
}
</style>


